package com.jtx.miaoah2.handler;

import com.alibaba.fastjson.JSON;
import com.jtx.miaoah2.Cache.HotCache;
import com.jtx.miaoah2.Cache.HotKeyLocalCache;
import com.jtx.miaoah2.Common.RedisConstants;
import com.jtx.miaoah2.Mapper.SkGoodsMapper;
import com.jtx.miaoah2.Model.goods.DO.SkGoods;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author 季台星
 * @Date 2023 07 23 19 39
 */
@Component
@Slf4j
public class ScheduleHandler {
    /**
     * 定时清理记录用户请求数量
     */
//    @Scheduled(cron = "* * * * * ? *")
//    public void clearUserRequestCount(){
//        UserTokenInterceptor.userRequestCount.clear();
//    }

    /**
     * 刷新redis中热点数据信息
     */
    @Autowired
    private HotCache hotCache;

    @Autowired
    private HotKeyLocalCache hotKeyLocalCache;


    @Autowired
    private SkGoodsMapper skGoodsMapper;
    @Scheduled(cron = "0/5 * * * * ? ")
    public void refreshRedisHotKeyInfo(){
        ConcurrentHashMap<String, Integer> hotKeyCount = HotKeyInterceptor.hotKeyCount;
        if (hotKeyCount.isEmpty()){
            return;
        }
        log.info("刷入redis的最热数据：{}",hotKeyCount);
        //TODO:考虑使用管道命令
        hotKeyCount.forEach((keyInfo,hotNum) ->{
            if (!hotCache.addHotKet(RedisConstants.HOT_KEY,keyInfo)) {
                hotCache.addHotScore(RedisConstants.HOT_KEY, RedisConstants.HOT_KEY_NAME + keyInfo,hotNum);
            }
        });
        hotKeyCount.clear();
    }

    @Scheduled(cron = "0/10 * * * * ? ")
    public void refreshLocalCache(){
        //从redis中得到热点前一百的数据
        List<Long> ids = hotCache.getByHotScore(RedisConstants.HOT_KEY)
                .stream()
                .limit(100)
                .map(ele -> Long.valueOf(ele.replaceAll(RedisConstants.HOT_KEY_NAME, "")))
                .collect(Collectors.toList());
        if (ids.isEmpty()){
            return;
        }
        //到数据库中得到商品信息存入本地缓存中
        List<SkGoods> skGoods = skGoodsMapper.selectByIds(ids);
        Map<Long, String> localCacheInfo = skGoods.stream()
                .collect(Collectors.toMap(SkGoods::getId, skgood -> JSON.toJSONString(skGoods)));
        //刷新最新缓存到本地
        log.info("刷入最新的热点缓存数据为：{}",localCacheInfo);
        hotKeyLocalCache.localCache.putAll(localCacheInfo);
    }
}
